#include "Utility.h"


FILE_SRC_INFO * source = NULL;
int INITIALIZATION = 0;

void Release() {
    if (source) {
        for (int i = 0; source->src[i] != NULL; i++) {
            free(source->src[i]);
            source->src[i] = NULL;
        }
        source->line_nums = 0;
        free(source);
        source = NULL;
        INITIALIZATION = 0;
    }
}

void Init() {
    /* Handle Wild pointer issue */
    if (INITIALIZATION != 0 && INITIALIZATION != 1) {
        INITIALIZATION = 0;
    }
    if (source != NULL) {
        source = NULL;
    }
    
    if (INITIALIZATION == 0) {
        INITIALIZATION = 1;
        source = (FILE_SRC_INFO*)malloc(sizeof(FILE_SRC_INFO));
        source->line_nums = 0;
        for (int i = 0; i < FILE_LINES; i++) {
            source->src[i] = NULL;
        }
    }
    return;
}

void ReadFile(const char * fileName) {
    FILE * file = NULL;
    
    fopen_s(&file, fileName, "r+");
    // open successfully
    if (file) {
        int i = 0;    
        char buffer[LINE_NUMBERS];
        while (1) {
            memset(buffer, 0, LINE_NUMBERS * sizeof(char));
            if (fgets(buffer, LINE_NUMBERS, file)) {
                size_t len = strlen(buffer);
                if (source->src[i] == NULL)
                    source->src[i] = (char*)calloc(LINE_NUMBERS, sizeof(char));
                // if (buffer[len-1] == '\n') 
                //     len = len - 1;
                memcpy(source->src[i], buffer, len);
                i++;
            } else {
                break;
            }
        }
        source->line_nums = i;
#if DEBUG
        for (int j = 0; j < i; j++)
            printf("%s", source->src[j]);
        _flushall();
#endif
        fclose(file);
    } else {
        printf("Can not open file: %s!", fileName);
    }
}

void SaveFile(const char * fileName, const void * content) {
    FILE * file = NULL;

    fopen_s(&file, fileName, "w");
    if (file) {
        fwrite(content, sizeof(char), strlen((char*)content), file);
        fclose(file);
    } else {
        printf("Can not open file: %s!", fileName);
    }
}